package ltd.newbee.mall.product.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @SuppressWarnings("unchecked")
    private Map<Long, Integer> getCart(HttpSession session) {
        Object obj = session.getAttribute("CART");
        if (obj instanceof Map<?, ?> map) {
            return (Map<Long, Integer>) map;
        }
        Map<Long, Integer> created = new HashMap<>();
        session.setAttribute("CART", created);
        return created;
    }

    @GetMapping
    public Map<Long, Integer> list(HttpSession session) {
        return getCart(session);
    }

    @PostMapping("/add/{productId}")
    public Map<Long, Integer> add(@PathVariable Long productId,
                                  @RequestParam(defaultValue = "1") Integer qty,
                                  HttpSession session) {
        Map<Long, Integer> cart = getCart(session);
        cart.put(productId, cart.getOrDefault(productId, 0) + Math.max(1, qty));
        return cart;
    }

    @PostMapping("/set/{productId}")
    public Map<Long, Integer> set(@PathVariable Long productId,
                                  @RequestParam Integer qty,
                                  HttpSession session) {
        Map<Long, Integer> cart = getCart(session);
        if (qty == null || qty <= 0) {
            cart.remove(productId);
        } else {
            cart.put(productId, qty);
        }
        return cart;
    }

    @DeleteMapping("/remove/{productId}")
    public Map<Long, Integer> remove(@PathVariable Long productId, HttpSession session) {
        Map<Long, Integer> cart = getCart(session);
        cart.remove(productId);
        return cart;
    }

    @PostMapping("/clear")
    public Map<Long, Integer> clear(HttpSession session) {
        Map<Long, Integer> cart = getCart(session);
        cart.clear();
        return cart;
    }
}



